import { defineConfig, loadEnv, UserConfig, ConfigEnv } from 'vite';
import { createProxyConfig, createPlugins, resolvePath } from './build';

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const envConfig = loadEnv(mode, process.cwd()) as unknown as ImportMetaEnv;
  const { VITE_PORT, VITE_HOST, VITE_CLEAN_CONSOLE } = envConfig;
  const isProduction = mode === 'production';
  // 获取env配置
  const proxy = createProxyConfig(envConfig);
  const plugins = createPlugins(mode, envConfig);
  return {
    plugins,
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "./src/styles/var.less";`,
        },
      },
    },
    resolve: {
      alias: {
        src: resolvePath('./src'),
      },
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.less', '.css', '.html', '.md'],
    },
    server: {
      host: VITE_HOST,
      port: Number(VITE_PORT) || 3000,
      open: true,
      proxy,
    },
    build: {
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          manualChunks(id) {
            // 由于引用指向了.pnpm 如果只过滤node_modules，包将构建到.pnpm-xxx.js中 导致文件过大
            // 根据依赖路径，将依赖包构建到对应目录下
            let target = id.toString();
            if (id.includes('node_modules')) {
              if (target.includes('.pnpm')) {
                const deps = target.split('.pnpm')[1];
                target = deps;
              }
              return target.split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
      minify: 'terser',
      terserOptions: {
        maxWorkers: 4,
        compress: {
          keep_infinity: true,
          drop_console: VITE_CLEAN_CONSOLE,
          dead_code: true,
        },
      },
    },
    define: {
      __PRODUCTION__: isProduction,
    },
  };
});
